<template>
  <div>
    <div class="search_box">
      <el-form
        :inline="true"
        ref="ruleFormRef"
        :model="formData"
        @submit.prevent
      >
        <el-form-item label="企业名称：">
          <el-input
            v-model="formData.tenantName"
            placeholder="请输入企业名称"
            clearable
            @clear="getList(1)"
          />
        </el-form-item>

        <el-form-item label="联系人：">
          <el-input
            v-model="formData.realName"
            placeholder="请输入联系人"
            clearable
            @clear="getList(1)"
          />
        </el-form-item>
        <el-form-item label="手机号：">
          <el-input
            v-model="formData.phone"
            placeholder="请输入手机号"
            clearable
            @clear="getList(1)"
          />
        </el-form-item>
        <el-form-item label="登录账号：">
          <el-input
            v-model="formData.userName"
            placeholder="请输入登录账号"
            clearable
            @clear="getList(1)"
          />
        </el-form-item>
        <el-form-item label="分类名称">
          <el-select
            v-model="formData.categoryId"
            placeholder="请选择分类名称"
            @clear="getList(1)"
            clearable
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item?.id"
              :label="item.name"
              :value="item?.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getList(1)">查 询</el-button>
          <el-button type="primary" @click="reset">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_box_wrapper">
      <div class="category">
        <div>
          {{ `将选中的 ${selectData?.length} 个分销商分类修改为：` }}
          <el-select
            v-model="categoryId"
            placeholder="请选择分类名称"
            clearable
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item?.id"
              :label="item.name"
              :value="item?.id"
            />
          </el-select>
          <el-button
            style="margin-left: 10px"
            type="primary"
            @click="update"
            :disabled="!selectData.length"
          >
            修改分类
          </el-button>
        </div>

        <div class="category_right">
          <el-button type="primary" @click="add">
            <el-icon style="margin-right: 5px">
              <Plus />
            </el-icon>
            新 增
          </el-button>
          <el-button type="primary" @click="categoryManage">
            <el-icon style="margin-right: 5px">
              <Folder />
            </el-icon>
            分类管理
          </el-button>
        </div>
      </div>
      <custom-table
        ref="tableRef"
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :pageObj="pageObj"
        :typeSelect="true"
        @sizechange="sizechange"
        @currentChange="currentChange"
        @selectionChange="selectionChange"
        @sortChange="sortChange"
        :isCustomHead="true"
        class="table_box"
      >
        <!-- <template #categoryName>
          <el-select
            v-model="formData.categoryId"
            placeholder="分类名称"
            @change="getList(1)"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item?.id"
              :label="item.name"
              :value="item?.id"
            />
          </el-select>
        </template> -->
        <template #enabled="{ scope }">
          <el-switch
            :modelValue="scope.row.enabled"
            style="

--el-switch-on-color: #13ce66"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            @click.stop="haddelStatus(scope.row)"
          />
        </template>
        <template #operator="{ scope }">
          <span class="operationClick" @click="handdel(scope.row, '编辑')">
            编辑
          </span>
          <span class="operationClick" @click="handdel(scope.row, '分类')">
            修改分类
          </span>
          <span class="operationClick" @click="handdel(scope.row, 'apiKey')">
            设置apiKey
          </span>
          <span class="operationClick" @click="handdel(scope.row, '分配')">
            分配小程序
          </span>
          <span class="operationClick" @click="handdel(scope.row, '收费')">
            价格设置
          </span>
        </template>
      </custom-table>
    </div>

    <!-- 分配小程序 -->
    <allocation ref="allocationRef" @success="getList(1)" />
    <!-- 新增编辑分销商 -->
    <distributorInfo ref="distributorRef" @success="getList(1)" />
    <!-- apiKey -->
    <apiKeyDialog ref="apiKeyRef" @success="getList(1)" />
    <!-- 分类管理 -->
    <categoryDialog ref="categoryRef" @success="getList(1)" />
    <!-- 分类管理 -->
    <setPrice ref="setPriceRef" @success="getList(1)" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import {
  searchTenant,
  categoryList,
  batchCategory,
  setEnabled,
} from "@/api/operateCenter/distributor/index";
import { Plus, Folder } from "@element-plus/icons-vue";
import type { Action } from "element-plus";
import allocation from "./components/allocationDialog.vue";
import distributorInfo from "./components/addDistributor.vue";
import apiKeyDialog from "./components/apiKeyDialog.vue";
import categoryDialog from "./components/categoryDialog.vue";
import setPrice from "./components/setPrice.vue";
import moment from "moment";

const loading = ref<boolean>(false);
const tableRef = ref();
const selectData = ref<Array<any>>([]);
const categoryOptions = ref<Array<any>>([]);
interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const form = {
  pageNo: 1,
  pageSize: 10,
  categoryId: undefined,
  tenantName: "",
  phone: "",
  userName: "",
  realName: "",
  sorting: "",
};
const formData = ref(Object.assign({}, form));
const tableData = ref<Array<any>>([]);
const categoryId = ref();
const columns = reactive([
  { prop: "name", label: "企业名称", minWidth: 120 },
  { prop: "userName", label: "登陆账号", minWidth: 120 },
  { prop: "realName", label: "联系人姓名", minWidth: 110 },
  { prop: "phone", label: "联系人手机号", minWidth: 115 },
  {
    prop: "latestLoginAt",
    label: "最近登录时间",
    sortable: true,
    minWidth: 134,
    formatter: (row: Record<string, any>) => {
      if (!row?.latestLoginAt) return "";
      return moment(row?.latestLoginAt + "Z").format("YYYY-MM-DD");
    },
  },
  {
    prop: "createAt",
    label: "合作开始时间",
    sortable: true,
    minWidth: 134,
    formatter: (row: Record<string, any>) => {
      if (!row?.createAt) return "";
      return moment(row?.createAt + "Z").format("YYYY-MM-DD");
    },
  },
  {
    prop: "payAmount30d",
    label: "30天充值总额",
    sortable: true,
    minWidth: 134,
  },
  {
    prop: "latestPaymentAt",
    label: "最近充值时间",
    sortable: true,
    minWidth: 134,
    formatter: (row: Record<string, any>) => {
      if (!row?.latestPaymentAt) return "";
      return moment(row?.latestPaymentAt + "Z").format("YYYY-MM-DD");
    },
  },
  {
    prop: "newUsers30d",
    label: "30天新增用户数",
    sortable: true,
    minWidth: 148,
  },
  {
    prop: "latestNewUsersAt",
    label: "新增用户时间",
    sortable: true,
    minWidth: 134,
    formatter: (row: Record<string, any>) => {
      if (!row?.latestNewUsersAt) return "";
      return moment(row?.latestNewUsersAt + "Z").format("YYYY-MM-DD");
    },
  },
  {
    prop: "latestLinkCreateAt",
    label: "推广链接创建时间",
    sortable: true,
    minWidth: 160,
    formatter: (row: Record<string, any>) => {
      if (!row?.latestLinkCreateAt) return "";
      return moment(row?.latestLinkCreateAt + "Z").format("YYYY-MM-DD");
    },
  },
  { prop: "enabled", slotName: "enabled", label: "是否启用", minWidth: 90 },
  {
    prop: "categoryName",
    label: "分类名称",
    // slotHeader: "categoryName",
    minWidth: 140,
  },
  {
    prop: "operator",
    slotName: "operator",
    label: "操作",
    width: 370,
    fixed: "right",
  },
]);

// 排序
const sortChange = (val: Record<string, any>) => {
  console.log("排序---", val);

  if (val?.order === "descending") {
    if (val.prop === "latestLinkCreateAt") {
      formData.value.sorting = "latestLinkCreateAt desc";
    } else if (val?.prop === "latestNewUsersAt") {
      formData.value.sorting = "latestNewUsersAt desc";
    } else if (val?.prop === "newUsers30d") {
      formData.value.sorting = "newUsers30d desc";
    } else if (val?.prop === "latestPaymentAt") {
      formData.value.sorting = "latestPaymentAt desc";
    } else if (val?.prop === "payAmount30d") {
      formData.value.sorting = "payAmount30d desc";
    } else if (val?.prop === "createAt") {
      formData.value.sorting = "createAt desc";
    } else if (val?.prop === "latestLoginAt") {
      formData.value.sorting = "latestLoginAt desc";
    }
  } else if (val?.order === "ascending") {
    if (val.prop === "latestLinkCreateAt") {
      formData.value.sorting = "latestLinkCreateAt asc";
    } else if (val?.prop === "latestNewUsersAt") {
      formData.value.sorting = "latestNewUsersAt asc";
    } else if (val?.prop === "newUsers30d") {
      formData.value.sorting = "newUsers30d asc";
    } else if (val?.prop === "latestPaymentAt") {
      formData.value.sorting = "latestPaymentAt asc";
    } else if (val?.prop === "payAmount30d") {
      formData.value.sorting = "payAmount30d asc";
    } else if (val?.prop === "createAt") {
      formData.value.sorting = "createAt asc";
    } else if (val?.prop === "latestLoginAt") {
      formData.value.sorting = "latestLoginAt asc";
    }
  } else {
    formData.value.sorting = "";
  }
  getList(1);
};

// 分类管理
const categoryRef = ref();
const categoryManage = () => {
  categoryRef.value.showDialog();
};

// 修改分类
const update = () => {
  let params = {
    categoryId: categoryId.value,
    tenantIds: selectData.value.map((x: Record<string, any>) => {
      return x.id.toString();
    }),
  };
  if (!params.categoryId) return ElMessage.error("请选择分类名称");
  batchCategory(params).then(() => {
    selectData.value = [];
    tableRef.value.elTableRef.clearSelection();
    ElMessage.success("修改成功");
    getList(1);
  });
};

// 启用
const haddelStatus = (row: Record<string, any>) => {
  ElMessageBox.alert(
    `确定要${row.enabled ? "禁用" : "启用"} "${row.userName}" 这个分销商吗？`,
    "提醒",
    {
      confirmButtonText: "确定",
      callback: (action: Action) => {
        if (action == "confirm") {
          setEnabled({ id: row?.id.toString(), enabled: !row.enabled }).then(
            () => {
              ElMessage.success(`${row.enabled ? "禁用" : "启用"}成功`);
              getList(1);
            }
          );
        }
      },
    }
  );
};

// 新增
const distributorRef = ref();
const add = () => {
  distributorRef.value.showDialog();
};

// 操作
const allocationRef = ref();
const apiKeyRef = ref();
const setPriceRef = ref();
const handdel = (row: Record<string, any>, str: string) => {
  if (str === "分配") {
    allocationRef.value.showDialog(row);
  } else if (str === "编辑") {
    distributorRef.value.showDialog(row);
  } else if (str === "apiKey") {
    apiKeyRef.value.showDialog(row);
  } else if (str === "分类") {
    categoryRef.value.showDialog(row);
  } else if (str === "收费") {
    setPriceRef.value.showDialog(row);
  }
};

// 重置
const reset = () => {
  Object.assign(formData.value, form);
  categoryId.value = "";
  getList(1);
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.value.pageNo = pageObj.pageNo;
  //   formData.value.pageSize = pageObj.pageSize;
  // } else {
  //   formData.value.pageNo = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.value.pageSize = pageObj.pageSize =
  //     val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.value.pageNo = pageObj.pageNo;
  formData.value.pageSize = pageObj.pageSize;

  formData.value.categoryId = (formData.value.categoryId ||
    undefined) as undefined;
  formData.value.sorting = (formData.value.sorting || undefined) as string;
  loading.value = true;
  searchTenant(formData.value)
    .then((res: Record<string, any>) => {
      tableData.value = res?.data || [];
      pageObj.total = Number(res?.total);
    })
    .finally(() => {
      loading.value = false;
    });
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

const selectionChange = (val: Array<any>) => {
  selectData.value = val;
};

// 获取分类管理列表
const getCategoryList = () => {
  categoryList().then((res: any) => {
    categoryOptions.value = res;
  });
};

onMounted(() => {
  getList();
  getCategoryList();
});
</script>
<style scoped lang="scss">
.table_box_wrapper {
  padding-top: 10px;
  margin-top: 15px;
  background-color: #fff;

  .category {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;
    font-size: 15px;
    color: #636363;

    .category_right {
      margin-right: 98px;
    }
  }
}
</style>
